class MagicPair
  def initialize(n)
    unless n.class.superclass.eql? Integer
      raise ArgumentError, 'Argument is not a numeric.'
    end
    unless n > 1
      raise ArgumentError, 'Argument is not bigger than 1.'
    end

    @n = n
    @maximum_magic = {
      :product => 0,
      :pair => []
    }

    @uniqueness = {}

    calculate_magic_pairs
  end

  def get_number_of_pairs
    @uniqueness.keys.size
  end

  def get_maximum_product_and_pair
    @maximum_magic
  end

  private

  def same_digits_as_in_product_of?(multiplier1, multiplier2)
    digits_of_product = (multiplier1 * multiplier2).to_s.split(//).sort
    digits_of_multipliers = (multiplier1.to_s.split(//) + multiplier2.to_s.split(//)).sort
    digits_of_product.eql?(digits_of_multipliers)
  end

  def calculate_magic_pairs
    def collect_unique_pairs
      1.upto(@n) {|a|
        a.upto(@n) {|b|
          if same_digits_as_in_product_of?(a, b)
            magic_pair = []
            magic_pair << a << b
            magic_pair.sort!
            @uniqueness[magic_pair] = a * b
          end
        }
      }
    end

    def find_maximum_product
      @maximum_magic[:product] = @uniqueness.values.max.nil? ? 0 : @uniqueness.values.max
      @uniqueness.each_key {|pair|
        @maximum_magic[:pair] << pair if @uniqueness[pair].eql? @maximum_magic[:product]
      }
    end

    collect_unique_pairs()
    find_maximum_product()
  end

end

N = 51
magic_pair = MagicPair.new N
puts "Number of unique pairs: #{magic_pair.get_number_of_pairs}"
puts "Maximum product: #{magic_pair.get_maximum_product_and_pair[:product]}; Corresponding pairs: #{magic_pair.get_maximum_product_and_pair[:pair].inspect}"

#produces:
# Number of unique pairs: 4
# Maximum product: 1530; Corresponding pairs: [[30, 51]]
